package com.ry.websocket.config;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;

@ServerEndpoint(value = "/test/{name}")
//@Component
public class OneWebSocket {

	private static ConcurrentHashMap<String, OneWebSocket> webSocketMap = new ConcurrentHashMap<String, OneWebSocket>();
	
	private Session session;
	
	private String name = "";
	

	/**
	 * 连接建立成功调用的方法
	 */
	@OnOpen
	public void onOpen(Session session, @PathParam("name") String name) {
		this.session = session;
		this.name = name;
		webSocketMap.put(name, this);
		
		System.out.println("【服务端】建立连接，客户端id为"+name);
		System.out.println("session = "+session.getId());
	}

	/**
	 * 连接关闭调用的方法
	 */
	@OnClose
	public void onClose(Session session) {
		webSocketMap.remove(this.name);
		
		System.out.println("关闭一处连接");
		
	}

	/**
	 * 收到客户端消息后调用的方法
	 *
	 * @param message
	 *            客户端发送过来的消息
	 */
	@OnMessage
	public void onMessage(String message, Session session) {
		System.out.println(String.format("服务端收到客户端["+name+"]的消息:"+message));
		//这里是收到消息群发给建立连接的用户，也可做单用户的回发
		try {
			for(String key : webSocketMap.keySet()) {
				OneWebSocket item = webSocketMap.get(key);
				item.sendMessage(message);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@OnError
	public void onError(Session session, Throwable error) {
		System.out.println("[error]发生错误");
		error.printStackTrace();
	}

	/**
	 * 服务端发送消息给客户端
	 * @throws IOException 
	 */
	public void sendMessage(String message) throws IOException {
		this.session.getBasicRemote().sendText(message);
	}
	
	/**
	 * 群发/单发（根据是否有用户名）
	 * @param message
	 * @param name
	 */
	public static void sendInfo(String message, @PathParam("name") String name) {
		
		try {
			for(String key : webSocketMap.keySet()) {
				OneWebSocket item = webSocketMap.get(key);
				if(name == null) {
					item.sendMessage(message);
				}else if(name.equals(key)) {
					item.sendMessage(message);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
